package actions;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import java.util.*;
import entities.*;

import javax.ejb.Local;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import utils.*;
import beans.*;

public class AddItemAction extends ActionSupport {

	private static final long serialVersionUID = 10L;

	// Comment for JBoss
	@EJB
	private BookManager bookManager = new BookManagerBean();

	private String message;
	private Item item;

	public AddItemAction() {

		message = "";
		item = new Item();
	}

	public String execute() {

		Object userIdObj = ActionContext.getContext().getSession()
				.get("userId");
		if (userIdObj == null) {
			this.addActionError("UserID is null");
			return ERROR;
		}
		if (item.getTitle() == null || item.getType() == null
				|| item.getVisible() == null || item.getLocation() == null) {
			this
					.addActionError("One or more of the required fields are not filled");
			ActionContext.getContext().getSession().put("error",
					"One or more of the required fields are not filled");
			return ERROR;
		}
		item.setUserId(((Integer) userIdObj).intValue());
		boolean copyAdded = bookManager.addCopy(item);
		message = item.getTitle() + " of type " + item.getType();
		if (!copyAdded) {

			message += " cannot be added to our systems. Please try again.";
			this.addActionError(message);
			ActionContext.getContext().getSession().put("error", message);
		} else {
			message += " was successfully added in our system";
			this.addActionError(message);
		}
		return SUCCESS;
	}

	public Item getItem() {
		return item;
	}

	public void setItem(Item item) {
		this.item = item;
	}

}